package com.taoyibao.hongcanting.ui.admin.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityNoSlidePresenter;
import com.taoyibao.hongcanting.base.delegate.ToolbarDelegate;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.dialog.DialogComment;
import com.taoyibao.hongcanting.event.EventCurrentPage;
import com.taoyibao.hongcanting.event.EventJPushCallBack;
import com.taoyibao.hongcanting.event.EventTabCount;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.ui.admin.delegate.AdministratorDelegate;
import com.taoyibao.hongcanting.ui.admin.fragment.CompletedTaskFragment;
import com.taoyibao.hongcanting.ui.admin.fragment.NewTaskFragment;
import com.taoyibao.hongcanting.ui.login.activity.LoginActivity;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.JPushUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushMessage;

/**
 * @author TangAnna
 * @description: 服务员操作
 * @date :${DATA} 15:53
 */
public class WaiterActivity extends BaseActivityNoSlidePresenter<AdministratorDelegate> implements ToolbarDelegate.OnTitleCliclListener {
    /**
     * 极光重新绑定tag的次数 最多尝试绑定3次
     */
    private int setTagCount = 0;

    @Override
    protected Class<AdministratorDelegate> getDelegateClass() {
        return AdministratorDelegate.class;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        viewDelegate.setFragmentManager(getSupportFragmentManager(), 2);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        isCheckTag();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        if (!TextUtils.isEmpty(SpUtils.getAdminNub())) {
            viewDelegate.setTitle(SpUtils.getAdminNub() + "号服务员");
        } else {
            viewDelegate.setTitle("服务员");
        }
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(NewTaskFragment.getInstance(CodeConstant.TASK_STATUS_NEW));
        fragments.add(CompletedTaskFragment.getInstance(CodeConstant.TASK_STATUS_FINISH));
        List<String> titles = new ArrayList<>();
        titles.add("新任务");
        titles.add("已完成");
        viewDelegate.addViewPageTab(fragments, titles);
        viewDelegate.setOffscreenPageLimit(fragments.size());
        //点击顶部退出
        viewDelegate.setOnTitleCliclListener(this);
    }

    /**
     * 判断是否添加屏幕操作员的tag成功
     */
    public void isCheckTag() {
        JPushUtils.checkTagBindState(JPushUtils.SEQUENCE_IDENTITY_0, JPushUtils.TAG_WAITER);
    }

    /**
     * 退出
     */
    public void logout() {
        JsonApiWrapper.getApiService().logout(SpUtils.getToken())
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel companyBaseModel) {
                        next();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        next();
                    }
                });
    }

    public void next() {
        LoginActivity.open(WaiterActivity.this, "WaiterActivity");
        finish();
        SpUtils.exist();
    }


    /**
     * 极光的回调
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMessage(EventJPushCallBack event) {
        if (event.type == CodeConstant.JPUSH_EVENT_TAG) {
            JPushMessage jPushMessage = event.mJPushMessage;
            if (!jPushMessage.getTagCheckStateResult()) {//未绑定成功
                if (setTagCount < 3) {//尝试重新设置tag
                    JPushUtils.setTags(JPushUtils.SEQUENCE_IDENTITY_0, JPushUtils.getWaiterTag());
                }
                setTagCount++;
            }
        }
    }


    /**
     * 切换当前页面的消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventPager(EventCurrentPage eventCurrentPage) {
        if (TextUtils.equals("AdminActivity", eventCurrentPage.target)) {
            viewDelegate.setCurrentPager(eventCurrentPage.mCurrentPage);
        }
    }

    /**
     * 顶部title的点击事件
     *
     * @param view
     */
    @Override
    public void onTitleClick(View view) {
        DialogComment dialogComment = new DialogComment(CodeUtils.getIdString(R.string.dialog_quit), new DialogComment.DialogCommentInterfaca() {
            @Override
            public void onConfirmListener() {
                logout();
            }
        });
        dialogComment.showDilaog(getSupportFragmentManager(), "AdministratorActivity");
    }

    //声明一个long类型变量：用于存放上一点击“返回键”的时刻
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                ToastUtils.showToast(CodeUtils.getIdString(R.string.dialog_isQuit));
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 数量变化时收到消息显示
     *
     * @param eventTabCount
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventCount(EventTabCount eventTabCount) {
        viewDelegate.setTabCount(eventTabCount.currentPager, eventTabCount.count);
    }
}
